<script setup lang="ts">
import { useElementSize } from '@vueuse/core';
import { AxesHelper, PerspectiveCamera, Scene, WebGLRenderer } from 'three'
import { watch, onBeforeUnmount, reactive, unref, onMounted, ref } from 'vue';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { boxmesh } from '../models'

const scene = new Scene()
const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)

boxmesh.position.set(300, 0, 0)
camera.lookAt(boxmesh.position)
scene.add(boxmesh)
const viewEleRef = ref<HTMLElement>(), canvasEle = ref<HTMLCanvasElement>()
const containerSizeInfo = reactive(useElementSize(viewEleRef))

let renderer: WebGLRenderer
camera.position.set(400, 300, 500)
watch(containerSizeInfo, (v) => {
  renderer.setSize(v.width, v.height)
  camera.aspect = v.width / v.height
  camera.updateProjectionMatrix()
})
function Render() {
  renderer.render(scene, camera)
  requestAnimationFrame(Render)
}
const axesIn = new AxesHelper(300)
onMounted(() => {

  renderer = new WebGLRenderer({ canvas: unref(canvasEle)! })
  new OrbitControls(camera, renderer.domElement)
  scene.add(axesIn)

  Render()
})

onBeforeUnmount(() => {
  renderer.dispose()
})

</script>

<template>
  <main ref="viewEleRef">
    <canvas :width="containerSizeInfo.width" :height="containerSizeInfo.height" ref="canvasEle"></canvas>
  </main>
</template>
<style>
main {
  height: 100%;
}
</style>